<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>录音 Demo</title>
</head>

<body>
  <h1>前端录音 Demo</h1>
  <button id="record-btn">开始录音</button>
  <button id="stop-btn" disabled>停止录音</button>
  <audio id="recorded-audio" controls></audio>

  <script>

    const recordButton = document.getElementById('record-btn');
    const stopButton = document.getElementById('stop-btn');
    const recordedAudio = document.getElementById('recorded-audio');

    let mediaRecorder;
    let audioChunks = [];

    recordButton.addEventListener('click', async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: true,

        });
        const options = { mimeType: 'audio/webm; codecs=opus' };
        mediaRecorder = new MediaRecorder(stream, options);

        mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            console.log('==event.data====>', event.data)
            audioChunks.push(event.data);
          }
        };

        mediaRecorder.start();

        recordButton.disabled = true;
        stopButton.disabled = false;
      } catch (e) {
        console.error('录音失败:', e);
      }
    });

    stopButton.addEventListener('click', async () => {
      recordButton.disabled = false;
      stopButton.disabled = true;
      mediaRecorder.stop()
      mediaRecorder.onstop = async () => {
        const audioBlob = new Blob(audioChunks, { type: 'audio/ogg; codecs=opus' });
        recordedAudio.src = URL.createObjectURL(audioBlob);
      };
    });


  </script>

</body>

</html>